<?php
/**
 * Created by PhpStorm.
 * User: 87393
 * Date: 2019-03-27
 * Time: 11:44
 */

namespace App\Http\Controllers\Admin\Api;


use App\Http\Controllers\Controller;
use App\Http\Repositories\Eloquent\Role;
use App\Http\Repositories\Services\IRole;
use App\Http\Requests\Admin\RoleInputDTO;
use App\Http\Requests\Admin\RolePermissionInputDTO;
use App\Util\LayUiVo;
use App\Util\ResultsVo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Lang;

class RoleController extends Controller
{

    protected $roleService;

    public function __construct(IRole $roleService)
    {
        $this->roleService = $roleService;
    }

    public function page(Request $request) {
        $search = [];
        $page = $request->get('page', 1);
        $size = $request->get('limit', 10);
        if ($request->get('name')) {
            $search['name'] = $request->get("name");
        }
        $data = $this->roleService->lists($search, $page, $size);
        return response()->json(new LayUiVo(['data'=>$data],[],['password','salt']));
    }

    public function store(RoleInputDTO $inputDTO)
    {
        $this->roleService->store($inputDTO);
        return response()->json(new ResultsVo(['message'=>Lang::get('response.success')]));
    }

    public function state($id, $state) {
        $this->roleService->state($id, $state);
        return response()->json(new ResultsVo(['message'=>Lang::get('response.success')],[],[]));
    }

    public function update(RoleInputDTO $inputDTO, $id)
    {
        $this->roleService->update($inputDTO,$id);
        return response()->json(new ResultsVo(['message'=>Lang::get('response.success')]));
    }


    public function permission(RolePermissionInputDTO $inputDTO,$id){
        $role = Role::findOrFail($id);
        $permissions = $inputDTO->get('permissions');
        if (empty($permissions)){
            $role->permissions()->detach();
        }else{
            $role->syncPermissions($permissions);
        }
        return response()->json(new ResultsVo(['message'=>Lang::get('response.success')]));
    }

}